//
//  game.cpp
//  Sinnca Engine v2
//
//  Created by Ryan Oldis on 6/13/11.
//  Copyright 2011 Sinnca Studios. All rights reserved.
//

#include "game.h"

#include "computer.h"
#include "Graphics.h"
#include "script.h"
#include "input.h"

#include "timer.h"
#include "Node.h"


void game::startup()
{
	cap = true;
	frameCap = 60;
	
	// Init SDL video subsystem
	if ( SDL_Init (SDL_INIT_EVERYTHING) < 0 ) {
		
        fprintf(stderr, "Couldn't initialize SDL: %s\n",
				SDL_GetError());
		exit(1);
	}
	
	
	Script->setVar("ENGINE VERSION", "0.0.1 : Pre-Alpha");
	
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	
	Graphics->createSurface();
	
	Graphics->init();
	Graphics->reshape();
	
	computer->printInfo();
	input->pad.printInfo();
	
}

void game::mainloop()
{
	bool done = false;
	
	printf("%d \n", SDL_GetTicks());
	Script->doFile(computer->fullPath + "/" + "main.lua");
	printf("%d \n", SDL_GetTicks());
	
	
	while (!done)
	{
		switch (tree->currentScene->state)
		{
			case sceneLoad:
				
				//just run for now...
				tree->currentScene->state = sceneRun;
				break;
				
			case scenePause:
				
				break;
				
			case sceneRun:
				globalTime->start();
		
				if (input->Update() == true)
				{
					done = true;
				}
				
				Script->mainUpdate();
				
				Graphics->render();
				SDL_Flip(Graphics->gScreen);
				SDL_GL_SwapBuffers();
				
				if ((cap == true) && (globalTime->getTicks() < 1000 / frameCap))
				{
					SDL_Delay((1000 / frameCap) - globalTime->getTicks());
					//printf("");
				}
				break;
				
			default:
				
				// if theres no valid sceneState... quit...
				done = true;
				break;
		}
	}
	
	
}

void game::cleanup()
{
	SDL_Quit();
}